<script setup lang='ts'>
import { reactive, ref, onMounted, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { CircleCloseFilled, Plus } from '@element-plus/icons-vue'
import type { IaddGoods } from '../../types/good'
import { imgBaseURL,apiBaseURL } from '@/api/baseURL'
import http from '../../api/http'
import type { ISpec } from '@/types/Spec'
import type { IgoodType } from '@/types/GoodsType'
import { VueUseComponentsResolver } from 'unplugin-vue-components/resolvers'

const types: IgoodType[] = reactive([])
const specs: ISpec[] = reactive([])
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<IaddGoods>({
    "gid":0,
    "name": "奈雪早餐",
    "content": "购买三明治,享早餐指定饮品半价",
    "images": "/static/picture/goods/fda6dd99c83af02353.jpg",
    "use_Spec": false,
    "use_Property":true,
    "unit": "件",
    "price": 18.5,
    "sales": 0,
    "sort": 0,
    "gtid": 1,
    "on_sale": true,
    "typeName": "奈雪早餐",
    goodsPropertyKey: [
         {
            gskid: 1,  //规格 主键表  GoodSpecKey  id
            goodsPropertyValue:[],
            checked: true,
            name:'食品口味'
          },
          {
            gskid: 2,
            goodsPropertyValue:[],
            checked: true,
            name:'温度'
          },
          {
            gskid: 3,
            goodsPropertyValue:[],
            checked: true,
             name:'糖度'
          }



    ]
})



//#endregion

//表单验证
const rules = reactive<FormRules<IaddGoods>>({
    name: [
        { required: true, message: '请输入姓名!', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在3-10个字符之间!', trigger: 'blur' },
    ],
    price: [
        { required: true, message: '请输入价格!', trigger: 'blur' },
    ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {

        if (valid) {
              let data = JSON.parse(JSON.stringify(ruleForm));
            console.log(data.goodPropertyKey)
            //axios 提交后台
           if (!data.use_Property) {
                data.goodPropertyKey =reactive([]);
            } else {
                data.goodPropertyKey.forEach(v => {
                     
                    if (!v.checked) {
                        data.goodsPropertyKey.push(...data.goodsPropertyKey.filter(v => v.checked));
                    }
                });
            }
            if (data.goodsPropertyKey.length < 1) {
                data.use_Property = false;
                ruleForm.use_Property = false;
            }



            http.put('Goods', data).then(res => {
                if (res.code == '1') {
                    ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                    dialogVisible.value = false
                    emit('refresh')
                }
                else {
                    ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }

            }).catch(err => {
                console.log('err: ', err);
            })


            //关闭弹窗 并刷新列表页面数据
            dialogVisible.value = false
            emit('refresh')
        } else {
            console.log('error submit!', fields)
        }
    })
}

//#region  父子组件之间双向绑定数据 数据传递
// 父子组件之间双向绑定数据 数据传递
const dialogVisible = defineModel<boolean>({required:true})
const emit = defineEmits<{ (e: 'refresh'): void }>()
const props = defineProps<{ formData: IaddGoods }>()
//监听key 的改变 并查询数据
watch(() => props.formData, (value:IaddGoods ) => {
    //切断数据关联
    let data: IaddGoods = JSON.parse(JSON.stringify(value))
 
    //form 赋值
    ruleForm.gid = data.gid;
    ruleForm.gtid = data.gtid;
    ruleForm.name = data.name;;
    ruleForm.images = data.images;
    ruleForm.use_Property = data.use_Property;
     ruleForm.use_Spec = data.use_Spec;
      ruleForm.on_sale = data.on_sale;
       ruleForm.unit = data.unit;
        ruleForm.price = data.price;
         ruleForm.sales = data.sales;
         ruleForm.sort = data.sort;
         ruleForm.goodPropertyKey=data.goodPropertyKey
          ruleForm.content=data.content
             ruleForm.goodsPropertyKey=data.goodsPropertyKey

    //ruleForm = data
    //console.log('ruleForm: ', ruleForm)

})

//#endregion
const propchange = () => {

    let bol = false;
    ruleForm.goodsPropertyKey.forEach(v => {
        if (v.checked) {
            bol = true;
        }
    })
    ruleForm.use_Property = bol;

}
onMounted(() => {

    http.get<ISpec[]>('Spec')
        .then(res => {
            specs.push(...res.data)
        })
        .catch(err => {
            console.log('err: ', err);
        })

    http.get<IgoodType[]>('GoodsType')
        .then(res => {
            types.push(...res.data)
        })
        .catch(err => {
            console.log('err: ', err);
        })
})

//#region 头像上传
const handleAvatarSuccess = (res: any) => {
   
    ruleForm.images = res.data.path
}
//上传之前
const beforeAvatarUpload = (file: any) => {
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'

    const isLtMB = file.size / 1024 / 1024 < 10

    if (!isJPG && !isPNG) {
        ElMessage.error('上传头像图片只能是 JPG 和 PNG 格式!')
    }
    if (!isLtMB) {
        ElMessage.error('上传头像图片大小不能超过 10MB!')
    }
    return (isJPG || isPNG) && isLtMB
}

</script>

<template>

    <el-dialog v-model="dialogVisible" :show-close="false" width="900" center>
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass"></h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left">
                        <CircleCloseFilled />
                    </el-icon>
                    关闭
                </el-button>
            </div>
        </template>
   <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px">
            <el-row>
                <el-col :span="6" :offset="1">
                    <el-form-item label="商品类型">
                        <el-select v-model="ruleForm.gtid" placeholder="请选择类型">
                            <el-option v-for="item in types" :key="item.gtid" :label="item.name"
                                :value="item.gtid"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品图片" prop="images">
                         <el-upload class="avatar-uploader" :action="apiBaseURL + 'Upload'" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="ruleForm.images" :src="imgBaseURL + ruleForm.images" class="avatar">
                    <el-icon v-else class="avatar-uploader-icon el-upload">
                        <Plus />
                    </el-icon>
                </el-upload>
                        <!-- <el-upload class="avatar-uploader" :action="imgBaseURL + 'Files'" :show-file-list="false"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="ruleForm.images" :src="imgBaseURL + ruleForm.images" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload> -->
                    </el-form-item>
                    <el-form-item label="商品名称" prop="name">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="price">
                        <el-input-number v-model="ruleForm.price" :precision="2" :step="1" :min="0"
                            style="width: 100px;"></el-input-number>
                    </el-form-item>
                    <el-form-item label="商品单位" prop="Unit">
                        <el-input v-model="ruleForm.unit"></el-input>
                    </el-form-item>
                    <el-form-item label="商品描述" prop="Content">
                        <el-input type="textarea" v-model="ruleForm.content"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="14" :offset="2">
                    <el-form-item label="属性">
                        <el-switch v-model="ruleForm.use_Property" active-color="#13ce66"
                            inactive-color="#ff4949"></el-switch>
                    </el-form-item>

                    <!-- 循环规格和规格的值 -->
                    <el-form-item v-for="(item, index) in specs" :key="item.gskid" :label="item.name"
                        v-show="ruleForm.use_Property">
                        <el-switch v-model="ruleForm.goodsPropertyKey[index].checked" @change="propchange"
                            active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                        <el-checkbox-group v-show="ruleForm.goodsPropertyKey[index].checked"
                            v-model="ruleForm.goodsPropertyKey[index].goodsPropertyValue">
                            <el-checkbox v-for="v in item.values" :name="item.name" :key=v.gsvid :label="v.gsvid"
                                :value="v.gsvid">
                                {{ v.value }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>


                </el-col>
            </el-row>


        </el-form>

       


        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>


<style scoped>
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>